﻿namespace RuoVea.ExSugar;

/// <summary>
/// 抽象基类
/// </summary>
public abstract partial class DbContext : IDbContext,IDisposable
{
    /// <summary>
    /// SqlSugarClient db
    /// </summary>
    public readonly SqlSugarClient db;

    /// <summary>
    /// 基类构造函数接收 ConnectionConfig 
    /// </summary>
    /// <param name="config"></param>
    public DbContext(ConnectionConfig config)
    {
        if (config == null)
            throw new ArgumentNullException($"未配置数据库链接");

        ConnectionConfig connection = config;
        connection.IsAutoCloseConnection = true;

        db = new SqlSugarClient(connection);
        db.Ado.IsEnableLogEvent = true;

        #region DataExecuting
        db.Aop.DataExecuting = (oldValue, entityInfo) =>
        {
            //新增操作
            if (entityInfo.OperationType == DataFilterType.InsertByObject)
            {
                if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
                    entityInfo.SetValue(IdGenerator.Id);

                if ( "CreateTime".Equals(entityInfo.PropertyName,StringComparison.OrdinalIgnoreCase))
                    entityInfo.SetValue(DateTime.Now);

                //if (entityInfo.PropertyName == "Creator" && App.User?.FindFirst(ClaimConst.CLAINM_USERID) != null)
                //    entityInfo.SetValue(App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value);
            }

            //更新操作
            if (entityInfo.OperationType == DataFilterType.UpdateByObject)
            {
                if ("ModifyTime".Equals(entityInfo.PropertyName, StringComparison.OrdinalIgnoreCase))
                    entityInfo.SetValue(DateTime.Now);

                //if (entityInfo.PropertyName == "Modifier" && App.User?.FindFirst(ClaimConst.CLAINM_USERID) != null)
                //    entityInfo.SetValue(App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value);
            }
        };
        #endregion

        #region OnLogExecuting
        db.Aop.OnLogExecuting = (sql, pars) =>
        {
            if (sql.StartsWith("SELECT"))
            {
                Console.ForegroundColor = ConsoleColor.Green;
            }
            if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
            {
                Console.ForegroundColor = ConsoleColor.White;
            }
            if (sql.StartsWith("DELETE"))
            {
                Console.ForegroundColor = ConsoleColor.Blue;
            }
            Console.WriteLine(SqlProfiler.ParameterFormat(sql, pars));
        };
        #endregion

        //执行超时时间
        db.Ado.CommandTimeOut = 30;

        #region OnLogExecuted
        //SQL执行完回调函数
        db.Aop.OnLogExecuted = (sql, pars) =>
        {
            //执行完可以输出SQL执行时间
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.Write($"耗时:TimeSpan:{db.Ado.SqlExecutionTime.TotalMilliseconds}ms" + "\r\n");
        };
        #endregion
    }

    /// <summary>
    /// Dispose
    /// </summary>
    public void Dispose()
    {
        if (db != null)
        {
            db.Dispose();
        }
    }
}
